import React, { useState, useEffect, useCallback } from 'react';
import { companyGettree } from '@/services/Organization/staffmanage';
import { Tree, Spin } from 'antd';
import styles from './index.less';

const { TreeNode } = Tree;

// 部门树
/**
 *
 * @param {String} defaultKeys 默认选中值
 * @param {Function} onSelect 点击部门事件，返回公司和部门id
 * @param {String} routeCode 路由权限code
 * @param {Array} partakeData 各个部门参与考核的人数
 * @param {Function} onFinish 加载完成后回调
 * @description 部门树
 */
const CompanyTree = ({ defaultKeys, onSelect, routeCode, partakeData, onFinish, ...rest }) => {
    const [loading, setLoading] = useState(false);
    // console.log(defaultKeys);
    const [data, setData] = useState([]);
    // 渲染树结构
    // 节点的key值由 cdType-companyId-id 拼接而成，节点的 value 值为id
    const renderTreeNodes = useCallback(
        nodes =>
            nodes.reduce((pre, item) => {
                const keys = `${item.cdType}-${item.companyId}-${item.cdType === 1 ? item.id : 0}`;
                const cItem = partakeData.find(
                    citem => keys === `${citem.cdType}-${citem.companyId}-${citem.departmentId}`
                );

                if (item.children) {
                    pre.push(
                        <TreeNode
                            title={`${item.name} (${item.employeeCount}/${cItem ? cItem.evalPeopleNum : 0})`}
                            key={keys}
                            value={item.id}
                            cdType={item.cdType}
                            companyId={item.companyId}
                        >
                            {renderTreeNodes(item.children)}
                        </TreeNode>
                    );
                } else {
                    pre.push(
                        <TreeNode
                            title={`${item.name} (${item.employeeCount}/${cItem ? cItem.evalPeopleNum : 0})`}
                            key={keys}
                            value={item.id}
                            cdType={item.cdType}
                            companyId={item.companyId}
                        ></TreeNode>
                    );
                }
                return pre;
            }, []),
        [data]
    );

    // 组件初始化拉取数据
    useEffect(() => {
        async function fetchData() {
            setLoading(true);

            // 待添加code
            const response = await companyGettree({ permissionUrl: '' }); // 拉取部门树数据
            if (response && response.code === 10000) {
                setData(response.data);
                if (onFinish) {
                    onFinish(response.data);
                }
            }
            setLoading(false);
        }
        fetchData();
    }, []);
    const loadTree = renderTreeNodes(data);

    // 点击节点回调
    const handleSelect = (selectedKeys, info) => {
        const { value, companyId, cdType } = info.node.props;
        const departmentId = cdType === 1 ? value : null; // 如果cdType===1 ？ id为部门id ：null

        // 将公司id和部门id传递给父组件
        if (onSelect) {
            onSelect({ departmentId, companyId, cdType });
        }
    };

    return (
        <Spin spinning={loading}>
            <div className={styles.companyTreeBox}>
                {data.length > 0 ? (
                    <>
                        <Tree
                            onSelect={handleSelect}
                            defaultExpandedKeys={[defaultKeys]}
                            defaultSelectedKeys={[defaultKeys]}
                            defaultExpandAll
                            {...rest}
                        >
                            {loadTree}
                        </Tree>
                    </>
                ) : null}
            </div>
        </Spin>
    );
};
export default CompanyTree;
